package handler

import (
	"demo/api/request"
	"demo/internal/dao"
	"demo/internal/model"
	"demo/internal/queue"
	"github.com/gin-gonic/gin"
	"net/http"
	"path/filepath"
)

func AddVideo(c *gin.Context) {
	var req request.VideoAddReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	video := model.Video{
		UserId: int64(req.UserId),
		Name:   req.Name,
		Sex:    req.Sex,
		Status: req.Status,
		People: int64(req.People),
		Gift:   int64(req.Gift),
	}
	if !dao.Create(&video) {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "直播间创建失败",
			"data": nil,
		})
		return
	}
	queue.QueueSub("product")
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "直播间创建成功",
		"data": video,
	})
}

func UpdateVideo(c *gin.Context) {
	var req request.UpdateVideoReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	video := model.Video{
		Id:     int64(req.Id),
		Status: req.Status,
	}
	if !dao.Update(&video) {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "修改状态失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "修改状态成功",
		"data": video,
	})
}

func UploadVideo(c *gin.Context) {
	var req request.UploadReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	file, _ := c.FormFile("file")
	dst := "./upload/upload" + file.Filename
	c.SaveUploadedFile(file, dst)
	if file.Filename == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "图片不能为空",
			"data": nil,
		})
		return
	}
	ext := filepath.Ext(file.Filename)
	if ext != ".png" && ext != ".jpg" {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "图片格式错误 重新上传",
			"data": nil,
		})
		return
	}
}

func ListVideo(c *gin.Context) {
	list := dao.ListUser()
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"data": list,
		"msg":  "展示成功",
	})
}

func RemoveVideo(c *gin.Context) {
	var req request.RemoveReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	video := model.Video{
		Id: int64(req.Id),
	}
	if !dao.Delete(&video) {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "删除失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"data": nil,
		"msg":  "删除成功",
	})
}
